import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { createTransport, Transporter } from 'nodemailer';
import { SMTPConfig } from '../../../libs/config/types';

@Injectable()
export class MailService {
  private transporter: Transporter;

  constructor(private configService: ConfigService) {
    const smtpConfig = this.configService.get<SMTPConfig>('mail');
    this.transporter = createTransport({
      host: smtpConfig.host,
      port: smtpConfig.port,
      secure: smtpConfig.secure,
      auth: {
        user: smtpConfig.user,
        pass: smtpConfig.password // 确保使用应用专用密码（16位）
      },
    });
  }

  async sendMail(to: string, subject: string, text: string): Promise<void> {
    const from = this.configService.get<string>('mail.defaultFrom');
    await this.transporter.sendMail({
      from,
      to,
      subject,
      text
    });
  }
}